package com.wc.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wc.demo.bo.UserInfoBo;
import com.wc.demo.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wc.demo.entity.UserInfo;
import com.wc.demo.mapper.UserMapper;
import com.wc.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,UserInfo> implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public List<UserInfoVo> getAllUser() {
        List<UserInfo> userInfo = userMapper.selectList(null);
        List<UserInfoVo> list=new ArrayList<>();
        for (UserInfo user : userInfo) {
            UserInfoVo userInfoVo=new UserInfoVo();
            BeanUtil.copyProperties(user, userInfoVo);
            list.add(userInfoVo);
        }
        return list;
    }

    @Override
    public UserInfoVo getUserById(Long id) {
        UserInfo userInfo = userMapper.getUserById(id);
//        UserInfo userInfo = lambdaQuery().eq(UserInfo::getId, id).one();
        UserInfoVo userInfoVo=new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    @Override
    public boolean saveOrUpdate(UserInfoBo userInfoBo) {
        UserInfo info=new UserInfo();
        BeanUtil.copyProperties(userInfoBo, info,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // info.setUserName(userInfoBo.getUserName());
        // info.setPassword(userInfoBo.getPassword());
        UserInfo userInfo = userMapper.getByName(info.getUserName());
        int isOK=0;
        if (userInfo!=null){
            info.setUpdateTime(LocalDateTime.now());
            //对象拷贝-忽略null(hutool的beanUtil)
            BeanUtil.copyProperties(info, userInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            isOK = baseMapper.updateById(userInfo);
        }else {
            info.setCreateTime(LocalDateTime.now());
            info.setUpdateTime(LocalDateTime.now());
             isOK = baseMapper.insert(info); // 使用 MyBatis-Plus 提供的插入方法
        }
        if (isOK > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean delById(Long id) {
        int isOK = baseMapper.deleteById(id); // 使用 MyBatis-Plus 提供的插入方法
        if (isOK > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public UserInfoVo getUserByName(String name) {
        UserInfo userInfo=userMapper.getByName(name);
        UserInfoVo userInfoVo=new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}
